<template>
    <!-- 主播选品 -->
    <el-tree class="mt-2" ref="deptTreeRef" node-key="id" :data="deptOptions"
        :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false" highlight-current show-checkbox
        :check-strictly="true" @check="handleChange" default-expand-all />
    <el-form ref="anchorSelectionDataRef" :model="anchorSelectionData" style="width: 100%" :inline="true"
        :rules="anchorSelectionrules" label-width="80px" @submit.prevent>
        <el-row class="hm-row3" :gutter="60">
            <el-col :span="24">
                <el-form-item label="直播类型" prop="liveType">
                    <el-radio-group v-model="anchorSelectionData.liveType">
                        <el-radio value="平播">平播</el-radio>
                        <el-radio value="打榜">打榜</el-radio>
                        <el-radio value="活动">活动</el-radio>
                        <el-radio value="大货">大货</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    <div class="dialog-footer">
        <el-button @click="anchorSelectionBeforeClose">取消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="anchorSelectionHandleSave(anchorSelectionDataRef)">
            提交
        </el-button>
    </div>
</template>
<script setup name="AnchorSelection" lang="ts">
import type { FormInstance } from 'element-plus'
import { changeCore, changeCoreIsAudit, deptTree, editCore, queryUserIdByDeptId } from '@/api/group/product/index'
import { type Action } from 'element-plus'
const props = defineProps(['id', 'isChange'])
const emit = defineEmits(['close', 'submit', 'onChangeSubmit'])
const deptOptions = ref([])
const deptTreeRef = ref()
const buttonLoading = ref(false);
// 当前选中的节点id
const currentNodeKey = ref()
// 主播名称
const coreName = ref()
// 直播类型ref
const anchorSelectionDataRef = ref()
// 直播类型
const anchorSelectionData = ref<any>({
    liveType: ''
})
// 直播类型rules
const anchorSelectionrules = ref({
    liveType: [
        { required: true, message: '请选择直播类型', trigger: 'change' },
    ],
})
/** 获取所有主播 */
const getDeptOptions = async () => {
    const { data } = await deptTree({ deptId: '1782395835898970113' })
    // 禁用电商主播和打榜部
    data.forEach((item: any) => {
        if (item.children && item.children.length > 0) {
            item.disabled = true
        }
    })
    deptOptions.value = data
}
/** 设置只能选择一个主播 */
const handleChange = (data: any) => {
    deptTreeRef.value.setCheckedKeys([data.id]);
    currentNodeKey.value = data.id
    coreName.value = data.label
}
/** 取消 */
const anchorSelectionBeforeClose = async () => {
    emit('close')
}
/** 重置缓存 */
const resetForm = () => {
    anchorSelectionData.value = {
        liveType: ''
    }
    currentNodeKey.value = undefined
    coreName.value = undefined
    anchorSelectionDataRef.value.resetFields()
}
/** 提交 */
const anchorSelectionHandleSave = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            if (!currentNodeKey.value) {
                ElMessage.error('请选择主播')
                return
            } else {
                try {
                    // 更改主播
                    if (props.isChange && Object.keys(props.isChange).length > 0) {
                        const resFlag = await changeCoreIsAudit({
                            id: props.id,
                            liveType: anchorSelectionData.value.liveType,
                            coreDeptId: currentNodeKey.value
                        })
                        // 重新送审
                        ElMessageBox.confirm(resFlag ? '将按照当前商品信息进行送审，是否确认提交？' : '即将变更主播信息/直播类型，请确认', '提示', {
                            confirmButtonText: '确认',
                            cancelButtonText: '取消',
                            callback: async (action: Action) => {
                                if (action == 'confirm') {
                                    buttonLoading.value = true
                                    try {
                                        await changeCore({
                                            id: props.id,
                                            liveType: anchorSelectionData.value.liveType,
                                            coreDeptId: currentNodeKey.value
                                        });
                                        resetForm();
                                        buttonLoading.value = false
                                        emit('onChangeSubmit')
                                    } catch {
                                        buttonLoading.value = false
                                    }
                                }
                            },
                        })
                    } else { // 选品部门
                        buttonLoading.value = true
                        try {
                            await editCore({
                                id: props.id,
                                coreId: currentNodeKey.value,
                                coreName: coreName.value,
                                liveType: anchorSelectionData.value.liveType,
                                coreDeptId: currentNodeKey.value
                            })
                            resetForm();
                            buttonLoading.value = false
                            emit('submit')

                        } catch {
                            buttonLoading.value = false
                        }
                    }
                } catch (err) {
                    console.error(err)
                }
            }
        }
    })
}
// 变更主播
onMounted(async () => {
    await getDeptOptions();
    if (props.isChange) {
        await nextTick(async () => {
            const res = await queryUserIdByDeptId({ userId: props.isChange.coreId })
            deptTreeRef.value.setCheckedKeys([res.data.deptId]);
            currentNodeKey.value = res.data.deptId;
            coreName.value = props.isChange.coreName;
            anchorSelectionData.value.liveType = props.isChange.liveType;
        });
    }
});
</script>